<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-06-09
 * Time: 21:04
 */

namespace app\common\service;

use app\common\service\WxAccessToken;
use think\facade\Config;
use think\facade\Log;

class WxMpSubscribeMessage
{
    private $sendUrl = ""; //发送消息模板的URL

    protected $template_id; //所需下发的模板消息的id
    protected $data;        //模板内容，不填则下发空模板
    protected $miniprogram_state = 'formal'; // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版

    public function __construct()
    {
        $accessToken = (new WxAccessToken('wx_mp1_access_token',get_wx_config('mp_app_id'), get_wx_config('mp_app_secret')))->get();
//        Log::record($accessToken . '|' . get_wx_config('mp_app_id') . '|' . get_wx_config('mp_app_secret'), 'error');

        $this->sendUrl = sprintf(Config::get('wx.mp_send_subscribe_message_url'),
            $accessToken);
    }

    /**
     * 发送订阅消息给指定的用户
     * @param $openid 用户的openid
     * @param string $page 点击模版卡片后调整的页面
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function sendSubscribeMessage($openid, $page = '')
    {
//        {
//            "touser": "OPENID",
//            "template_id": "TEMPLATE_ID",
//            "page": "index",
//            "miniprogram_state":"developer",
//            "lang":"zh_CN",
//            "data": {
//                    "number01": {
//                        "value": "339208499"
//              },
//              "date01": {
//                        "value": "2015年01月05日"
//              },
//              "site01": {
//                        "value": "TIT创意园"
//              } ,
//              "site02": {
//                        "value": "广州市新港中路397号"
//              }
//            }
//        }
        $data = [
            'touser'=>$openid,
            'template_id'=>$this->template_id,
            'page'=>$page,
            'data'=>$this->data,
            'miniprogram_state'=>$this->miniprogram_state
        ];

        $result = curl_post($this->sendUrl,$data);

        if (!$result) {
            throw new \Exception('请求数据发送错误，url:'. $this->sendUrl);
        }

        $result = json_decode($result, true);

        if ($result['errcode'] != 0) {
            throw new \Exception('小程序发送订阅消息失败，code：'.$result['errcode'].',msg：'.$result['errmsg']);
        }
    }
}